unit Gnome;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

const
  n=66;
  nr=33;
  a=15;
  b=5;
  r=100;
  h=30;
  l=10;

type
  TForm1 = class(TForm)
    Panel1: TPanel;
    Timer1: TTimer;
    Button1: TButton;
    ScrollBar1: TScrollBar;
    Label1: TLabel;
    Label2: TLabel;
    Button2: TButton;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    Label6: TLabel;
    Label7: TLabel;
    Label8: TLabel;
    Label9: TLabel;
    Label10: TLabel;
    Label11: TLabel;
    Label12: TLabel;
    Label13: TLabel;
    Label14: TLabel;
    Label15: TLabel;
    Label16: TLabel;
    Label17: TLabel;
    Label18: TLabel;
    Label19: TLabel;
    Label20: TLabel;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure ScrollBar1Change(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  p:array [0..n] of TPanel;
  tic, tac,x,y:integer;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var i:integer;
begin
  for i:=0 to n-1 do
  begin
    p[i]:=TPanel.Create(Form1);
    p[i].Parent:=Form1;
    p[i].Height:=a;
    p[i].Width:=a;
    p[i].Top:=h+b*(i div nr -1)+a*(i div nr);
    p[i].Left:=l+a*(i mod nr)+b*(i mod nr -1);
  end;
  y:=n*(n-1) div 2;
  Label20.Caption:=IntToStr(y);
end;

procedure TForm1.Button1Click(Sender: TObject);
var i:integer;
begin
  Timer1.Enabled:=true;
  Timer1.Interval:=1000 - ScrollBar1.Position*10;
  for i:=0 to n-1 do
  begin
    p[i].Caption:=IntToStr(random(r));
    p[i].Color:=clBtnFace;
  end;
  tic:=n-2;
  tac:=0;
  x:=0;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
var t:string;
begin
  p[tic+1].Color:=clYellow;
  p[tic].Color:=clGreen;
  if StrToInt(p[tic].Caption)>StrToInt(p[tic+1].Caption) then
  begin
    t:=p[tic].Caption;
    p[tic].Caption:=p[tic+1].Caption;
    p[tic+1].Caption:=t;
    tic:=tic+1;
    x:=x+1;
    if tic=n-1 then
    begin
      p[tic].Color:=clGreen;
      tac:=tac+1;
      tic:=n-2-tac;
    end;
  end
  else
  begin
    p[tic+1].Color:=clGreen;
    x:=x+n-1-tic;
    tac:=tac+1;
    tic:=n-2-tac;
  end;
  if tac=n-1 then
    Timer1.Enabled:=False;
  Label18.Caption:=IntToStr(x);
end;

procedure TForm1.ScrollBar1Change(Sender: TObject);
begin
  Timer1.Interval:=1000 - ScrollBar1.Position*10;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  if tac<n-1 then
    Timer1.Enabled:=not Timer1.Enabled;
end;

end.
